package gweb

// 系统变量支持

type VariableFunc func(c *Context) any

type Variable struct {
	Name     string       `json:"name"`
	Key      string       `json:"key"`
	Module   string       `json:"module"` // 适用场景
	GetValue VariableFunc `json:"-"`
}

type VariableView struct{}

func (view *VariableView) RegisterRoutes(router *RouterGroup) {
	router.GET("/system/variables", view.getVaiables)
	router.POST("/system/variables", view.getVariableValue)
	router.GET("/system/variable/:key", view.getVariableValue)
}

func (view *VariableView) getVaiables(c *Context) {
	app := c.App
	c.SuccessWithData(app.variables)
}

func (view *VariableView) getVariableValue(c *Context) {
	key := c.Param("key")
	if key == "" {
		c.Fail("系统变量key不能为空")
	}
	app := c.App
	for _, v := range app.variables {
		if v.Key == key {
			c.SuccessWithData(map[string]any{
				key:     key,
				"value": v.GetValue(c),
			})
			return
		}
	}
	c.Failf("未找到系统变量: %s", key)
}

func (app *GinApp) RegisterVariable(v Variable) {
	app.variables = append(app.variables, v)
}
